import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;



public class JpegRecovery {
	File f;
	JpegRecovery(File f){
		this.f = f;
	}
	boolean recover(){
		if (f.getName().startsWith("REC_")){
			return false;
		}
		File newFile = new File(f.getParent()+"/REC_"+f.getName());
		FileInputStream fi = null;
		FileOutputStream fo =  null;
		int jpeg_head[] = { 0xff, 0xd8,0xff, 0xe1, 0xff, 0xfe,0x45, 0x78, 0x69,0x66 };
		try {
			fi = new FileInputStream(f);
			fo = new FileOutputStream(newFile);
			byte data[] = new byte[1024];
			int l = fi.read(data);
			int eq_counter = 0;
			boolean found = false;
			while (l > 0 ){
				if (found) {
					fo.write(data,0,l);
				} else {
					for (int i = 0; i < l; i++) {
						
						if (data[i] == (byte)jpeg_head[eq_counter]) {
							eq_counter++;
						} else {
							eq_counter = 0;
						}
						if (eq_counter == jpeg_head.length) {
							for (int j = 0; j < jpeg_head.length; j++) {
								fo.write(jpeg_head[j]);
							}
							fo.write(data,i,l-i); 
							found = true;
							break;
						}
					}
				}
				l = fi.read(data);
			}
			if (!found) {
				throw new Exception("no jpeg"); 
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			newFile.delete();
			return false;
		} finally {
			try {
				fi.close();
			}catch (Exception e) {
			}
			try {
				fo.close();
			} catch (Exception e) {
			}
		}
		
		
		
		
	}
}
